<template>
  <div class="app-box" id="applyInfo">
    <loading :show="isloading" :text="loadingtex"></loading>
    <step v-show="showStep" v-model="step1" background-color='#fbf9fe'>
      <step-item title="填卡"></step-item>
      <step-item title="资料"></step-item>
      <step-item title="完成"></step-item>
    </step>
    <group @click.native="showStep=false">
      <x-input title="信用卡号" type="tel" placeholder="0000 0000 0000 0000" text-align="right" v-model="personForm.cardNo" :max="19" disabled mask="9999 9999 9999 9999"></x-input>
      <x-input title="CVN2" text-align="right" placeholder="输入卡片背面签名条3位数字" v-model="personForm.cvn2" :min="3" :max="3" type="number"></x-input>
      <x-input title="有效期" text-align="right" placeholder="MMYY,2018年3月到期即为0318" v-model="personForm.expiryDate" :min="4" :max="4" type="number"></x-input>
      <x-input title="姓名" name="username" text-align="right" placeholder="输入持卡人姓名" v-model="personForm.custName" is-type="china-name"></x-input>
      <x-input title="身份证号" text-align="right" placeholder="输入18位证件号,末尾以X代替*" v-model="personForm.idNo" :min="18" :max="18"></x-input>
      <x-input title="预留手机号" text-align="right" placeholder="请输入银行预留手机号" v-model="personForm.hpNo" :max="13" is-type="china-mobile"></x-input>
    </group>
    <div class="into-pab into-pab1">
      <div style="margin: 10px 0 15px 0; font-size:14px;color:#999;">
        <check-icon :value.sync="checkValue"> <span style="color:#999;">我已阅读并同意</span></check-icon>
        <router-link to="/registrationagreement">《注册协议》</router-link>
        <div style=" margin-left: 35px;">注：扣款方为银俊科技</div>
        <div style=" margin-left: 63px;">每期为25天</div>
      </div>
      <div class="plr">
        <x-button type="primary" :disabled="!isNext1" @click.native="showDialog = true">下一步</x-button>
      </div>
      <div v-transfer-dom class='step2Dialog'>
        <popup v-model="showDialog" height="90%" is-transparent>
          <div style="width: 96%;background-color:#fff;height:98%;border-radius:5px;margin:auto auto;">
            <div class="img_payment"><img slot="right-full-height" :src="img_payment"></div>
            <group label-width="8em" label-align="left">
              <x-input title="商品金额" placeholder="商品金额" text-align="right" v-model="personForm.goods_amount" disabled>
                <span slot="right" class="colorblack">元</span>
              </x-input>
              <x-input title="分期期数" text-align="right" v-model="personForm.stageCount" disabled>
                <span slot="right" class="colorblack">期</span>
              </x-input>
              <x-input title="每期预计还款金额" placeholder="商品金额" text-align="right" v-model="personForm.eachPayMoney" disabled>
                <span slot="right" class="colorblack">元</span>
              </x-input>
              <x-input title="短信验证码" :show-clear="false" class="weui-vcode" v-model="personForm.verifyCode" :max="4" type="tel">
                <x-button slot="right" type="primary" style="position:" @click.native="sendMsg" :disabled="!sendBtn">{{sendMsgInfo}}</x-button>
              </x-input>
            </group>
            <div style="padding:20px 15px;">
              <x-button type="primary" :disabled="!isConfirm" @click.native="submitForm">确认</x-button>
              <x-button @click.native="showDialog = false">取消</x-button>
            </div>
          </div>
        </popup>
      </div>
    </div>
  </div>
</template>
<script>
import { Group, XInput, XButton, Alert, Cell, Selector, Card, Flexbox, FlexboxItem, Step, StepItem, CheckIcon, TransferDom, Popup, XNumber, Loading } from 'vux'
import { installpay, senddx } from '@/api/apply'
// import { constants } from 'http2'
import img_payment from '@/assets/img_payment.png'

import { removeAllSpace, cloneObj } from '@/utils/common'
import { setTimeout } from 'timers'
export default {
  directives: {
    TransferDom
  },
  components: {
    XInput,
    XButton,
    Group,
    Cell,
    Alert,
    Selector,
    Card,
    Flexbox,
    FlexboxItem,
    Step,
    StepItem,
    CheckIcon,
    Popup,
    XNumber,
    Loading
  },
  data() {
    return {
      checkValue: false,
      step1: 1,
      showStep: true,
      showDialog: false,
      img_payment,
      createQuery: {},
      submitQuery: {},
      sendMsgInfo: '发送验证码',
      countdown: 60,
      lastTime: '',
      isHaveTime: false,
      // isNext1: false,
      personForm: {
        // 'bankcard': '6217855300025633474',
        'cardNo': this.$route.params.cardNo, // 卡号
        'cvn2': '316',
        'expiryDate': '0622', // 有效期
        'custName': '李丹', // 姓名
        'idNo': '533325198401107164', // 身份证
        'hpNo': '18616952720', // 手机
        'goods_amount': this.$route.params.goods_amount, // 总金额
        'stageCount': this.$route.params.stageCount,
        'stageAmt': this.$route.params.stageAmt,
        'eachPayMoney': this.$route.params.eachPayMoney, // 每期金额
        'openId': this.$route.query.openid,
        'orderId': this.$route.params.orderId,
        'orderIddes': this.$route.params.orderIddes,
        'bankCode': this.$route.params.bankCode,
        'merNo': this.$route.params.merNo,
        'channelNo': this.$route.params.channelNo,
        'prdtNo': this.$route.params.prdtNo
      },
      getFromPre: {
        prdtNo: this.$route.params.prdtNo,
        phNo: '', // 手机
        channelNo: this.$route.params.channelNo,
        verifyCode: '', // 验证码
        scene_id: this.$route.query.sceneId,
        custName: '', // 姓名
        idNo: '', // 身份证
        lfq_cnt: this.$route.params.lfq_cnt,
        lfq_amt: this.$route.params.lfq_amt,
        cardNo: '',
        cvn2: '', // cvn2
        expiryDate: '', // 有效期
        merId: this.$route.params.merNo,
        cardFeeRate: this.$route.params.custRate,
        goods_amount: this.$route.params.goods_amount,
        lng: '1.0',
        lat: '2.0',
        debitCard: '',
        bankCode: this.$route.params.bankCode,
        apply_id: this.$route.query.apply_id,
        pay_id: this.$route.query.pay_id,
        orderId: this.$route.params.orderIddes,
        tookenkey: this.$route.params.tookenkey,
        locCity: '1',
        locProv: '1',
        detailAddr: '1',
        servlet_type: 'create_order'
      },
      isloading: false,
      loadingtex: '提交中'
      // getFromPre: this.$route.params,
    }
  },
  computed: {
    isNext1: function() {
      let regId = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      let regTel = /^1[0-9]{10}$/

      let isnext = this.personForm.cvn2 && this.personForm.expiryDate && this.personForm.custName && this.personForm.idNo && this.personForm.hpNo && this.checkValue && regId.test(this.personForm.idNo) && regTel.test(this.personForm.hpNo)
      // console.log('isnext==' + isnext)
      return isnext
    },
    sendBtn: function() {
      let cansend = !this.isHaveTime
      return cansend
    },
    isConfirm: function() {
      let regCode = /(^\d{4}$)/
      let isnext = this.personForm.verifyCode && regCode.test(parseInt(this.personForm.verifyCode))
      // console.log('isConfirm==' + isnext)
      return isnext
    }

  },
  created() {},
  methods: {
    // 获取验证码
    sendMsg() {
      this.isloading = true
      this.loadingtex = '请求发送验证码'
      this.personForm.cardNo = removeAllSpace(this.personForm.cardNo)
      this.lastTime = new Date().getTime()
      this.countdownTime()
      debugger
      var _sendparams = cloneObj(this.personForm)
      _sendparams.ph_no = this.personForm.phNo
      _sendparams.orderid = this.personForm.orderIddes
      _sendparams.id_no = this.personForm.idNo
      //     _sendparams.channelNo = '02'
      senddx(_sendparams).then(res => {
        this.isloading = false
        debugger
        let resData1 = res.data
        if (resData1.code !== '0000') {
          this.$vux.alert.show({
            title: '提示',
            content: resData1.msg
          })
        }
        debugger
        if (resData1.data && resData1.data.applyId) {
          this.personForm.applyId = resData1.data.applyId
          this.personForm.payId = resData1.data.payId
        }
      }).catch(error => {
        this.isloading = false
        console.log('senddx error=' + error)
      })
    },
    // 120倒计时,程序挂载时,继续执行
    countdownTime() {
      var _scountdown = sessionStorage.getItem('countdown')
      if (_scountdown && _scountdown != 'NaN') {
        this.countdown = sessionStorage.getItem('countdown')
      } else {
        this.countdown = 60
      }
      var _lastcountdown = parseInt(this.countdown)
      var sihadle = setInterval(() => {
        var nowTime = new Date().getTime()
        var cTimes = Math.floor((nowTime - this.lastTime) / 1000)
        this.countdown = _lastcountdown - cTimes
        this.isHaveTime = true
        this.sendMsgInfo = '重新发送(' + this.countdown + ')'
        if (this.countdown < 0) {
          this.countdown = 0
        }
        if (this.countdown == 0) {
          this.showRefresh = true
          clearInterval(sihadle)
          this.isHaveTime = false
          this.sendMsgInfo = '发送验证码'
          this.countdown = 60
        }
        // console.log('this.sendMsgInfo==' + this.sendMsgInfo)
        sessionStorage.setItem('countdown', this.countdown)
      }, 1000)
    },
    submitForm() {
      // 去除空格
      this.getFromPre.cardNo = removeAllSpace(this.$route.params.cardNo)
      this.getFromPre.debitCard = removeAllSpace(this.$route.params.cardNo)
      const createQuery = this.getFromPre
      createQuery.verifyCode = this.personForm.verifyCode
      createQuery.creditName = this.personForm.custName
      createQuery.cust_name = this.personForm.custName
      createQuery.creditNo = this.personForm.cardNo
      createQuery.idno = this.personForm.idNo
      createQuery.orderId = this.personForm.orderIddes
      createQuery.card_end_date = this.personForm.expiryDate
      createQuery.cvn2 = this.personForm.cvn2
      createQuery.phoneNo = this.personForm.hpNo
      createQuery.orderIdeny = this.personForm.orderIddes
      createQuery.exp = this.personForm.expiryDate
      createQuery.bankCode = this.personForm.bankCode
      createQuery.applyId = this.personForm.applyId
      createQuery.payId = this.personForm.payId
      // console.log('submitForm==' + JSON.stringify(query))
      this.isloading = true
      this.loadingtex = '正在支付'
      installpay(createQuery).then(res => {
        this.isloading = false
        let _data = res
        if (res.data) {
          _data = res.data
        }
        this.retnFunc(_data)
      }).catch(error => {
        this.isloading = false
        this.$vux.alert.show({
          title: '提示',
          content: '支付失败'
        })
        throw error
      })
    },
    //  交易回调处理函数
    retnFunc(retn) {
      var tipmsg = "init";
      var resmsg = "";
      var des_openid = "";
      var errorCode = ''

      debugger
      if (retn.lft_orderinfo_response != undefined) {
        if (retn.lft_orderinfo_response.resp_code == "0000") { //如果成功 
          //this.$route.params.returnurl
          this.$router.push({ path: '/tradeResult', query: { serial_no: this.payCode, resultCode: '03', returnurl: this.$route.params.returnurl } })
          return
        } else {
          errorCode = retn.lft_orderinfo_response.resp_code;
        }
      } else if (retn.error_business_response && retn.error_business_response.code == "0000") { // 交易成功
        this.$router.push({ path: '/tradeResult', query: { openid: this.open_id, sceneId: this.sceneId, serial_no: this.payCode, resultCode: '03', returnurl: this.$route.params.returnurl } })
        return;
      }
      // code 为59时失败 跳转到提示页面 为56时失败 跳转到提示页面
      if (retn.error_business_response.code == "59" || retn.error_business_response.code == "56") {
        tipmsg = retn.error_business_response.msg;
        this.$router.push({ path: '/tradeResult', query: { errormsg: tipmsg, resultCode: retn.error_business_response.code, serial_no: this.payCode, returnurl: this.$route.params.returnurl } })
        return
      }
      if (retn.error_business_response) {
        // 可修改的提示
        if (retn.error_business_response) {
          resmsg = retn.error_business_response.msg;
          tipmsg = retn.error_business_response.msg;
        } else if (retn.error_response != undefined) {
          resmsg = retn.error_response.resp_code;
          tipmsg = retn.error_response.resp_msg ? retn.error_response.resp_msg : retn.error_response.sub_msg;
        } else if (retn.user_acct_response != undefined) {
          resmsg = retn.user_acct_response.is_black;
          des_openid = retn.des_open_id;
        } else if (retn.error_business_response) {
          tipmsg = retn.error_business_response.sub_msg;
        } else {
          tipmsg = "当前服务请求出错，请重新查询";
        }

        if (resmsg == 'WRONG0001') {
          tipmsg = "短信验证码出错";
        } else if (resmsg == 'WRONG999') {
          tipmsg == "申请服务异常";
        }
      } else {
        debugger
        errorCode = retn.error_business_response.code;
        let errorMsg = retn.error_business_response.msg ? retn.error_business_response.msg : retn.error_business_response.sub_msg
        this.$router.push({ path: '/tradeResult', query: { errormsg: errorMsg, resultCode: errorCode, serial_no: this.payCode, returnurl: this.$route.params.returnurl } })
      }




      if (tipmsg != "init") {
        this.$vux.alert.show({
          title: '提示',
          content: tipmsg
        })
      }
    }

  }
}

</script>
<style lang="less" scoped>
.bgblue {
  background: #007EE9!important;
  color: #fff!important;
}

.colorblack {
  color: #333;
}

.step2Dialog {
  .img_payment {
    img {
      display: block;
      width: 100%;
    }
  }
  .weui-label {
    width: auto;
  }
}

#applyInfo {
  font-size: 14px;

  .weui-cells {
    margin-top: 0;
  }
  .weui-cells:after {
    margin: 0 10px;
  }
  .weui-cell:before {
    margin-right: 10px;
  }
  .weui-vcode {
    .weui-label {
      width: 6em;
    }
  }
}

.into-pab1 {
  position: absolute;
  bottom: 10px;
  width: 100%;
}

</style>
